package com.yelink.metrics.api;

import cn.hutool.json.JSONUtil;
import com.yelink.metrics.api.dto.MetricsUpsertDTO;
import com.yelink.metrics.api.dto.TriggerCallbackDTO;
import com.yelink.metrics.api.dto.common.CommonMaterialEntity;
import com.yelink.metrics.api.time.DailyVO;
import com.yelink.metrics.api.time.MonthlyVO;
import com.yelink.metrics.api.time.WeeklyVO;
import com.yelink.metrics.core.domain.ResponseData;

import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.List;


/**
 * 默认的, 套用feign
 * @author idea
 */
@Slf4j
public class DefaultMetricsApiImpl implements MetricsApi {

    @Resource
    private MetricsFeign metricsFeign;

    @Override
    public void triggerCallback(TriggerCallbackDTO o) {
        metricsFeign.triggerCallback(o);
    }

    @Override
    public void refreshMetrics(MetricsUpsertDTO dto) {
        metricsFeign.refreshMetrics(dto);
    }

    @Override
    public DailyVO getDaily() {
        Object r = metricsFeign.getDaily();
        return getR(r, DailyVO.class);
    }



    @Override
    public WeeklyVO getWeekly() {
        Object r = metricsFeign.getWeekly();
        return getR(r, WeeklyVO.class);
    }

    @Override
    public MonthlyVO getMonthly() {
        Object r = metricsFeign.getMonthly();
        return getR(r, MonthlyVO.class);
    }


    @Override
    public Collection<CommonMaterialEntity> getCommonMaterialEntitys(List<String> materialCodes) {
        Object r = metricsFeign.getCommonMaterialEntitys(materialCodes);
        return getRList(r, CommonMaterialEntity.class);
    }

    public static <T> T getR(Object feignR, Class<T> clazz) {
        ResponseData responseData = JSONUtil.toBean(JSONUtil.parseObj(feignR), ResponseData.class);
        if(responseData.getData() == null) {
            return null;
        }
        return JSONUtil.toBean(JSONUtil.parseObj(responseData.getData()), clazz);
    }

    public static <T> Collection<T> getRList(Object feignR, Class<T> clazz) {
        ResponseData responseData = JSONUtil.toBean(JSONUtil.parseObj(feignR), ResponseData.class);
        if (responseData.getData() == null) {
            return null;
        }
        return JSONUtil.toList(JSONUtil.parseArray(responseData.getData()), clazz);
    }
}
